import utils, { NameSpace } from 'utils';
import exceed from 'utils/apimap';
import { navigate } from 'utils/router';
import { ENUM } from 'utils/constants.js';
import { Message } from '@teamix/ui';
import { getProjectSize, getProjectGC, postProjectGC } from 'api';
import intl from '../../../../../../../../../locale';

const ns = NameSpace('PROJECT_SETTINGS');
const { pathResource, organization } = window.FORCE;
let checkTransferTimeout;
let GCTimer;
export const UPDATE_DATA = ns('UPDATE_DATA');
export const RESET_DATA = ns('RESET_DATA');
export const RECEIVE_REPO_SETTING = ns('RECEIVE_REPO_SETTING');

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

export function resetData() {
  return (dispatch) => {
    dispatch({
      type: RESET_DATA,
    });
  };
}

// 获取库信息
export function getProject() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'projects.single.get',
        params: {
          id: pathResource.id,
        },
      })
      .then((result) => {
        result.visibility_level = utils.processVisibilityLevel(Number(result.visibility_level));
        updateData({
          projectInfo: utils.processVisibilityLevel(result),
        })(dispatch);
      });
  };
}

export function getSourceProject() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'project.forked.source.project',
        params: {
          id: pathResource.id,
        },
      })
      .then((res) => {
        updateData({
          sourceProjectVisibilityLevel: res.visibility_level,
        })(dispatch);
      });
  };
}

export function checkIsForked() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'project.is.forked',
        params: {
          id: pathResource.id,
        },
      })
      .then((res) => {
        updateData({
          isForked: res.result,
        })(dispatch);
        if (res.result === true) {
          getSourceProject()(dispatch);
        }
      });
  };
}

export function saveGeneral(data, callback) {
  return () => {
    callback(true);
    exceed
      .fetch({
        api: 'projects.settings.edit',
        params: {
          id: pathResource.id,
        },

        data,
      })
      .then(() => {
        callback(false);
        Message.success({
          title: intl.get({
            id: 'code-assets.settings.actions.SavedSuccessfully',
            defaultMessage: '保存成功',
          }),
        });

        window.location.reload();
      })
      .fail(() => {
        callback(false);
      });
  };
}

export function searchBranches(search, callback) {
  return () => {
    exceed
      .forceFetch({
        api: 'projects.all.branches.search',
        params: {
          id: pathResource.id,
        },

        data: {
          search,
        },
      })
      .then((result) => {
        callback(
          result.list.map((e) => ({
            label: e.name,
            value: e.name,
          })),
        );
      });
  };
}

export function searchNamespaces(search, callback) {
  return () => {
    exceed
      .forceFetch({
        api: 'organization.owned',
        data: {
          search,
        },
      })
      .then((result) => {
        callback(result);
      });
  };
}

export function archiveOrUnarchive(isNeddedArchive) {
  return () => {
    exceed
      .forceFetch({
        api: isNeddedArchive ? 'project.archive' : 'project.unarchive',
        params: {
          id: pathResource.id,
        },
      })
      .then((result) => {
        if (result.result === true) {
          Message.success({
            title: isNeddedArchive
              ? intl.get({
                  id: 'code-assets.settings.actions.ArchivedSuccessfully',
                  defaultMessage: '归档成功',
                })
              : intl.get({
                  id: 'code-assets.settings.actions.ArchivedSuccessfully.1',
                  defaultMessage: '解除归档成功',
                }),
          });

          window.location.reload();
        } else {
          Message.error({
            title: isNeddedArchive
              ? intl.get({
                  id: 'code-assets.settings.actions.FailedToArchive',
                  defaultMessage: '归档失败',
                })
              : intl.get({
                  id: 'code-assets.settings.actions.FailedToUnarchive',
                  defaultMessage: '解除归档失败',
                }),
          });
        }
      });
  };
}

// 回调处理弹窗状态
export function transfer(data, callback) {
  return () => {
    callback({
      submitting: true,
      isModalOpen: true,
    });

    exceed
      .fetch({
        api: 'project.setting.transfer',
        params: {
          projectId: pathResource.id,
          groupId: data.groupId,
        },

        data,
      })
      .then(() => {
        Message.success({
          title: intl.get({
            id: 'code-assets.settings.actions.DatabaseTransferSucceeded',
            defaultMessage: '库转移成功',
          }),
        });

        navigate(`/${data.path_with_namespace}/settings`, { state: { forceUpdate: true } });
        callback && callback();
      })
      .fail(() => {
        Message.error({
          title: intl.get({
            id: 'code-assets.settings.actions.FailedToTransferTheDatabase',
            defaultMessage: '库转移失败',
          }),
        });
      });
  };
}

export function rename(data, callback) {
  return () => {
    callback({
      submitting: true,
      visible: true,
    });

    exceed
      .forceFetch({
        api: 'projects.settings.rename',
        params: {
          id: pathResource.id,
        },

        data,
      })
      .then(() => {
        const prefix = window.location.pathname.match(/(.*)\/.*\/settings/)[1];
        Message.success({
          title: intl.get({
            id: 'code-assets.settings.actions.LibraryPathUpdated',
            defaultMessage: '库路径更新成功',
          }),
        });

        callback({
          submitting: false,
          visible: false,
        });

        window.location.href = `${prefix}/${data.path}/settings`;
      })
      .catch(() => {
        callback({
          submitting: false,
        });
      });
  };
}

export function checkTransfer(successCallback, failedCallback) {
  return exceed
    .forceFetch({
      api: 'project.status.get',
      params: {
        id: pathResource.id,
      },
    })
    .then((result) => {
      if (checkTransferTimeout) {
        clearTimeout(checkTransferTimeout);
      }
      if (result.transfer_status === ENUM.project_transfer_status.SUCCESS) {
        clearTimeout(checkTransferTimeout);
        successCallback && successCallback(result);
      } else if (result.transfer_status === ENUM.project_transfer_status.WRONG) {
        clearTimeout(checkTransferTimeout);
        failedCallback && failedCallback(result);
      } else {
        checkTransferTimeout = setTimeout(() => {
          checkTransfer(successCallback, failedCallback);
        }, 1000);
      }
    });
}

// 获取大小
export function getSize() {
  return (dispatch) => {
    getProjectSize()
      .then((result) => {
        updateData({
          repo_size: result.repo_size,
        })(dispatch);
      })
      .catch((err) => {
        console.error(err);
      });
  };
}
// 获取GC
export function getGC(isNeedRefreshReposize) {
  return (dispatch) => {
    getProjectGC()
      .then((result) => {
        updateData({
          GC: result,
        })(dispatch);
        // GC 状态为started，每隔1s请求一次
        if (result.status === 'started') {
          if (GCTimer) {
            clearTimeout(GCTimer);
          }
          GCTimer = setTimeout(() => {
            dispatch(getGC(true));
          }, 1000);
        } else if (isNeedRefreshReposize) {
          // 状态变更，更新repoSize
          dispatch(getSize());
        }
      })
      .catch((err) => {
        console.error(err);
      });
  };
}
// 执行GC
export function postGC(immediately) {
  return (dispatch) => {
    updateData({
      isPostingGC: true,
    })(dispatch);
    postProjectGC(immediately)
      .then((result) => {
        updateData({
          GC: result,
          isPostingGC: false,
        })(dispatch);
        // GC 状态为started，每隔1s请求一次
        if (result.status === 'started') {
          if (GCTimer) {
            clearTimeout(GCTimer);
          }
          GCTimer = setTimeout(() => {
            dispatch(getGC(true));
          }, 1000);
        }
      })
      .catch((err) => {
        updateData({
          isPostingGC: false,
        })(dispatch);
        console.error(err);
      });
  };
}

// 页面跳转清楚定时器
export function clearTimer() {
  return () => {
    if (checkTransferTimeout) {
      clearTimeout(checkTransferTimeout);
    }
    if (GCTimer) {
      clearTimeout(GCTimer);
    }
  };
}

// 查询企业设置
export function getRepoSettingData() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'organization.repo.setting.get',
        params: {
          org_id: organization.id,
        },
      })
      .then((result) => {
        dispatch({
          type: RECEIVE_REPO_SETTING,
          data: result,
        });
      });
  };
}
